package com.autobet.services;

import com.alibaba.fastjson.JSONObject;
import com.autobet.dao.CommonDao;
import com.autobet.model.support.AutoResult;
import com.autobet.model.support.BetBean;
import com.autobet.model.table.Account;
import com.autobet.model.table.AutoHis;
import com.autobet.model.table.ResultHis;
import com.autobet.services.thread.BetThread;
import com.autobet.services.thread.CheckResultThread;
import com.autobet.services.thread.CheckSystemThread;
import com.autobet.services.thread.QueryResultThread;
import com.autobet.utils.BetUtils;
import com.autobet.utils.HttpUtils;
import com.autobet.utils.IdGenerator;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * Created by yangd on 2017-08-27.
 */
@Service
public class BetService {

    private static final Logger log = LoggerFactory.getLogger(BetService.class);
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private ResultService resultService;
    private int iLastResultQuery = 0;
    private Map realBetMap = new HashMap();
    private Map realDoBuydateIdMap = new HashMap();
    private static Map<String, String> autohisrmap = new HashMap();

    public BetService() {
    }

    public boolean initBetEnv(String accountId, String cookie, String preAmount, String intervalTime) throws Exception {
        try {
            EnvConfigService.setAccountId(accountId);
            EnvConfigService.setTaskStatus("RUNING");
            EnvConfigService.setIntervalTime(intervalTime);
            EnvConfigService.setCookie(cookie);
            Account account = new Account();
            account.setPreAmount(preAmount);
            account.setRemark("客户配置");
            account.setInsertDate(new Date());
            account.setAccountId(accountId);
            account.setIntervalTime(intervalTime);
            this.commonDao.saveAccount(account);
            log.info("系统下单环境初始化成功");
            this.resultService.addInfo("系统下单环境初始化成功..");
            return true;
        } catch (Exception var6) {
            log.error("初始化下单环境失败", var6);
            return false;
        }
    }


    /**
     * 下注
     * @param betType
     * @throws Exception
     */
    public void doBet(String betType) throws Exception {
        try {
            AutoResult autoResult = this.resultService.getCurrentResultRetry(6);
            //开奖数据的保存
            ResultHis rh = this.commonDao.queryResultHisByBuydateId(autoResult.getBuydateId());
            if(rh == null || rh.getBuydateId() == null) {
                ResultHis resultHis = new ResultHis();
                resultHis.setDataId(IdGenerator.getSLId());
                resultHis.setBuydateId(autoResult.getBuydateId());
                resultHis.setInsertDate(new Date());
                resultHis.setFirstFlag("n");
                resultHis.setResultDate(BetUtils.getCurrDateYYYYMMDD());
                resultHis.setR1(autoResult.getBuyResultArray()[0]);
                resultHis.setR2(autoResult.getBuyResultArray()[1]);
                resultHis.setR3(autoResult.getBuyResultArray()[2]);
                resultHis.setR4(autoResult.getBuyResultArray()[3]);
                resultHis.setR5(autoResult.getBuyResultArray()[4]);
                resultHis.setR6(autoResult.getBuyResultArray()[5]);
                resultHis.setR7(autoResult.getBuyResultArray()[6]);
                resultHis.setR8(autoResult.getBuyResultArray()[7]);
                resultHis.setR9(autoResult.getBuyResultArray()[8]);
                resultHis.setR10(autoResult.getBuyResultArray()[9]);
                List<ResultHis> list = new ArrayList();
                list.add(resultHis);
                this.commonDao.saveOrUpdateResultHis(list);
            }

            JSONObject jsonobj;
            String closeTime;
            try {
                label72: {
                    closeTime = this.resultService.getPridDataRetry(6);
                    log.info("请求返回的结果：{}", closeTime);
                    if(closeTime != null && closeTime.trim() != "") {
                        jsonobj = JSONObject.parseObject(closeTime);
                        if(jsonobj != null) {
                            break label72;
                        }

                        throw new Exception("取不到结果信息，可能登陆超时，请暂停系统，输入cookie重新开始");
                    }

                    throw new Exception("取不到结果信息，可能登陆超时，请暂停系统，输入cookie重新开始");
                }
            } catch (Exception var16) {
                throw new Exception("获取首次开奖期数以及结果失败！可能登陆超时，请重新尝试");
            }

            closeTime = jsonobj.getString("closeTime");
            String pBuydateId = jsonobj.getString("pnumber");
            String buydateId = jsonobj.getString("drawNumber");
            if(closeTime != null && pBuydateId != null && buydateId != null) {
                this.resultService.addInfo("上期" + pBuydateId + ",准备下注" + buydateId + "期");
                List<AutoHis> lastAutoHisList = this.commonDao.queryAutoHisByBuydateIdAndBetType(pBuydateId, betType);
                if(lastAutoHisList != null && lastAutoHisList.size() != 0) {
                    this.iLastResultQuery = 0;
                    AutoHis oneAutoHis = (AutoHis)lastAutoHisList.get(0);
                    if("00".equals(oneAutoHis.getBuyResult())) {
                        log.info("上期{}还未开奖，跳过下单，继续...", oneAutoHis.getBuydateId());
                        this.resultService.addInfo("上期" + oneAutoHis.getBuydateId() + "还未开奖，跳过下单，继续...");
                    } else {
                        List<AutoHis> currentAutohisList = this.commonDao.queryAutoHisByBuydateIdAndBetType(buydateId, betType);
                        if(currentAutohisList != null && currentAutohisList.size() > 0) {
                            log.info("{}期已下单，跳过继续...", buydateId);
                            this.resultService.addInfo(buydateId + "期已下单，跳过继续...");
                        } else {
                            List<AutoHis> preAutoList = this.commonDao.queryAutoHisByBuydateIdAndBetType(pBuydateId, betType);
                            ResultHis preResultHis = this.commonDao.queryResultHisByBuydateId(pBuydateId);
                            if(preResultHis == null) {
                                log.info("没有获取到开奖记录，下单跳过...");
                                this.resultService.addInfo("没有获取到开奖记录，下单跳过...");
                            } else if(this.checkStopRule("both")) {
                                this.stopBetForException("符合止损止盈规则..系统停止..");
                            } else {
                                ResultHis fResultHis = this.commonDao.queryResultHisByResultDateAndFirst(BetUtils.getCurrDateYYYYMMDD());
                                List<AutoHis> betList = this.simulateBet(preAutoList, "n", preResultHis, fResultHis.getBuydateId());
                                BetBean betBean = new BetBean();
                                betBean.setBuydateId(buydateId);
                                betBean.setBetList(betList);
                                this.realBetMap.put(buydateId + "_" + betType, betBean);
                                //开始下注
                                this.doAllRealBet(buydateId);
                            }
                        }
                    }
                } else {
                    log.info("没有获取到上一期{}的投注记录", pBuydateId);
                    this.resultService.addInfo("没有获取到上一期" + pBuydateId + "的投注记录，等待上期数据...");
                    ++this.iLastResultQuery;
                    if(this.iLastResultQuery > 10) {
                        throw new Exception("没有获取到上一期" + pBuydateId + "的投注记录，暂停系统，重新开始下单...");
                    }
                }
            } else {
                throw new Exception("取不到结果信息，可能登陆超时，请暂停系统，输入cookie重新开始");
            }
        } catch (Exception var17) {
            log.info("下单失败！", var17);
            this.stopBetForException("下单失败！请重新执行系统...");
            throw var17;
        }
    }

    public void doBetBeginEntry(String betType) throws Exception {
        if("RUNING".equals(EnvConfigService.getTaskStatus())) {
            log.info("系统已经在运行中######");
            throw new Exception("系统任务已经在执行中，为防止重复下单，请停止系统任务后重新执行!");
        } else {

            log.info("重新建表");
            this.resultService.addInfo("系统数据重建...", "02");
            this.commonDao.createTable();

            EnvConfigService.setTaskStatus("RUNING");

            this.doBetBegin();

        }
    }

    /**
     * 下注
     * @param buydateId
     * @throws Exception
     */
    public void doAllRealBet(String buydateId) throws Exception {
        try {
            BetBean dxBetBean = (BetBean)this.realBetMap.get(buydateId + "_" + "dx");
            if(dxBetBean == null) {
                log.info(buydateId + "期大小投注计算未结束,等待...");
                this.resultService.addInfo(buydateId + "期大小投注计算未结束,等待...");
                return;
            }

            BetBean dsBetBean = (BetBean)this.realBetMap.get(buydateId + "_" + "ds");
            if(dsBetBean == null) {
                log.info(buydateId + "期单双投注计算未结束,等待...");
                this.resultService.addInfo(buydateId + "期单双投注计算未结束,等待...");
                return;
            }

            if(!buydateId.equals(dxBetBean.getBuydateId()) || !buydateId.equals(dsBetBean.getBuydateId())) {
                throw new Exception("投注期数和准备的投注数据期数不一致！");
            }

            //下注JSON拼接
            StringBuffer paraJson = new StringBuffer();
            paraJson.append("{\"lottery\":\"BJPK10\",\"drawNumber\":\"").append(buydateId).append("\",\"bets\":[");

            for(int i = 1; i <= 10; ++i) {
                //获取大小投注数据
                Iterator var6 = dxBetBean.getBetList().iterator();

                AutoHis betAutoHis;
                while(var6.hasNext()) {
                    betAutoHis = (AutoHis)var6.next();
                    //车数

                    if(String.valueOf(i).equals(betAutoHis.getBuyNum()) && "true".equals(betAutoHis.getReadlyfalg())) {
                        paraJson.append("{\"game\":\"DX").append(betAutoHis.getBuyNum()).append("\",");
                        paraJson.append("\"contents\":\"").append(  betAutoHis.getBuyWhatReadly() ).append("\",");
                        paraJson.append("\"amount\":").append( betAutoHis.getBuyAmountReadly() ).append(",\"odds\":").append(EnvConfigService.getMoneytakeRate()).append("},");
                    }
                }

                //获取单双投注数据
                var6 = dsBetBean.getBetList().iterator();

                while(var6.hasNext()) {
                    betAutoHis = (AutoHis)var6.next();
                    if(String.valueOf(i).equals(betAutoHis.getBuyNum()) && "true".equals(betAutoHis.getReadlyfalg())) {
                        paraJson.append("{\"game\":\"DS").append(betAutoHis.getBuyNum()).append("\",");
                        paraJson.append("\"contents\":\"").append(betAutoHis.getBuyWhatReadly()).append("\",");
                        paraJson.append("\"amount\":").append(betAutoHis.getBuyAmountReadly()).append(",\"odds\":").append(EnvConfigService.getMoneytakeRate()).append("},");
                    }
                }
            }

            paraJson.deleteCharAt(paraJson.lastIndexOf(","));
            paraJson.append("],\"ignore\":false}");
            log.info("要投注的JSON串：{}", paraJson.toString());

            try {
                List<AutoHis> hisList = this.commonDao.queryAutoHisByBuydateId(buydateId);
                if(hisList != null && hisList.size() > 0) {
                    this.resultService.addInfo(buydateId + "期已下单，跳过继续...");
                    log.info(buydateId + "期已下单，跳过继续...");
                    return;
                }

                if(autohisrmap.get(buydateId) != null) {
                    log.info("去重判断！{}期已经保存过数据了", buydateId);
                } else {
                    autohisrmap.put(buydateId, "y");
                    this.commonDao.saveAutoHisList(dxBetBean.getBetList());
                    this.commonDao.saveAutoHisList(dsBetBean.getBetList());
                }
            } catch (Exception var9) {
                throw new Exception("投注记录保存到数据库失败！请重新尝试！具体原因:" + var9.getMessage());
            }

            log.info("下注记录保存数据库成功");
            this.resultService.addInfo(buydateId + "期下注记录保存数据库成功");

            //是否真实下注
            if("y".equals(EnvConfigService.getRealBetFlag())) {
                boolean betflag = false;

                try {
                    betflag = this.doRealBetRetry(3, buydateId, paraJson.toString());
                    if(!betflag) {
                        throw new Exception("下注失败，返回的状态不为0");
                    }
                } catch (Exception var8) {
                    log.info("实际下注失败！", var8.getMessage());
                    this.resultService.addInfo(buydateId + "期真实实际下注失败，原因:" + var8.getMessage() + ",系统继续尝试下注...", "02");
                    return;
                }

                this.resultService.addInfo(buydateId + "期真实下注成功...等待开奖...");
                log.info(buydateId + "期下注成功...等待开奖...");
            } else {
                this.resultService.addInfo(buydateId + "期模拟下注成功...等待开奖...");
                log.info(buydateId + "期模拟下注成功...等待开奖...");
            }

            //重置基数后改回正常状态
            if(EnvConfigService.clearFlag){
                EnvConfigService.clearFlag = false ;
            }

            this.realBetMap.remove(buydateId + "_" + "dx");
            this.realBetMap.remove(buydateId + "_" + "ds");
        } catch (Exception var10) {
            log.error("单双同时下单异常!");
            this.stopBetForException("单双同时下单异常!系统停止...");
        }

    }

    public void stopBet(boolean flag, String message) {
        EnvConfigService.setTaskStatus("STOP");
        if(flag) {
            this.resultService.addInfo(message, "01");
        }

    }

    public void stopBetForException(String message) {
        EnvConfigService.setWarningFlag("y");
        EnvConfigService.setTaskStatus("STOP");
        this.resultService.addInfo(message, "01");
    }

    /**
     * 验证停止规则
     * @param betType
     * @return
     * @throws Exception
     */
    public boolean checkStopRule(String betType) throws Exception {
        try {
            BigDecimal winAmount;
            if("y".equals(EnvConfigService.getCutDieFlag())) {
                log.info("判断穿版止损规则...");
                this.resultService.addInfo("判断穿版止损规则,穿版" + EnvConfigService.getDieCount() + "次止损...");
                winAmount = this.commonDao.queryMaxDieCountAutoHis(BetUtils.getCurrDateYYYYMMDD());
                /*使用静态类控制*/
                if(winAmount.intValue() >= Integer.parseInt(EnvConfigService.getDieCount())) {
                    log.info("{}投注日，有一路车已经被击穿{}次，系统停止投注...", BetUtils.getCurrDateYYYYMMDD(), Integer.valueOf(winAmount.intValue()));
                    this.stopBetForException(BetUtils.getCurrDateYYYYMMDD() + "投注日，有一路车已经被击穿" + winAmount.intValue() + "次，系统停止投注...");
                    return true;
                }
            }

            if("y".equals(EnvConfigService.getCutLostAmountFlag())) {
                log.info("判断金额止损规则...");
                this.resultService.addInfo("判断金额止损规则，止损金额:" + EnvConfigService.getCutLostAmount() + "...");
                winAmount = this.commonDao.queryRealAutoHisBuymoneytakeByResultDate(BetUtils.getCurrDateYYYYMMDD(), betType);
                if(winAmount.intValue() < 0) {
                    winAmount = winAmount.abs();
                }

                if(winAmount.intValue() > Integer.parseInt(EnvConfigService.getCutLostAmount())) {
                    log.info(BetUtils.getCurrDateYYYYMMDD() + "投注日实际投注金额已亏损到达" + winAmount.intValue() + "，系统止损设置" + EnvConfigService.getCutLostAmount() + "，系统止损，停止运行...");
                    this.stopBetForException(BetUtils.getCurrDateYYYYMMDD() + "投注日实际投注金额已亏损到达" + winAmount.intValue() + "，系统止损设置" + EnvConfigService.getCutLostAmount() + "，系统止损，停止运行...");
                    return true;
                }
            }

            if("y".equals(EnvConfigService.getCutWinFlag())) {
                log.info("判断金额止盈规则...");
                this.resultService.addInfo("判断金额止盈规则，止盈金额:" + EnvConfigService.getCutWinAmount() + "...");
                winAmount = this.commonDao.queryRealAutoHisBuymoneytakeByResultDate(BetUtils.getCurrDateYYYYMMDD(), betType);
                if(winAmount.intValue() > Integer.parseInt(EnvConfigService.getCutWinAmount())) {
                    log.info(BetUtils.getCurrDateYYYYMMDD() + "投注日实际投注金额已盈利到达" + winAmount.intValue() + "，系统盈利设置" + EnvConfigService.getCutLostAmount() + "，系统盈利，停止运行...");
                    this.stopBetForException(BetUtils.getCurrDateYYYYMMDD() + "投注日实际投注金额已盈利到达" + winAmount.intValue() + "，系统盈利设置" + EnvConfigService.getCutLostAmount() + "，系统盈利，停止运行...");
                    return true;
                }
            }

            return false;
        } catch (Exception var3) {
            log.error("判断止损止盈规则失败！", var3);
            this.resultService.addInfo("判断止损止盈规则异常！" + var3.getMessage(), "01");
            return true;
        }
    }

    /**
     * 开始投注
     * @throws Exception
     */
    public void doBetBegin() throws Exception {
        try {
            this.resultService.addInfo("系统准备开始投注..");

            JSONObject jsonobj;
            String closeTime;
            try {
                closeTime = this.resultService.getPridDataRetry(6);
                log.info("请求返回的结果：{}", closeTime);
                if(closeTime == null || closeTime.trim() == "") {
                    throw new Exception("登陆超时");
                }

                jsonobj = JSONObject.parseObject(closeTime);
                if(jsonobj == null) {
                    throw new Exception( "取不到结果信息，可能登陆超时，请暂停系统，输入cookie重新开始");
                }
            } catch (Exception var17) {
                throw new Exception("获取首次开奖期数以及结果失败！可能登陆超时，请重新尝试");
            }

            /*查询所有结果*/
            List<ResultHis> allList = this.resultService.getCurrentAllResultRetry(6);
            this.commonDao.saveOrUpdateResultHis(allList);

            for(int i = 0 ; i < allList.size() ; i++){
                this.resultService.buildSelect(allList.get(i));
            }
            QueryResultThread queryResultThread = new QueryResultThread("[queryResultThread1]");
            queryResultThread.start();
            this.resultService.addInfo("开启开奖结果查询任务成功...");
            CheckResultThread checkResultThread = new CheckResultThread();
            checkResultThread.start();
            this.resultService.addInfo("开启开奖结果检查任务成功...");
            CheckSystemThread checkSystemThread = new CheckSystemThread();
            checkSystemThread.start();
            this.resultService.addInfo( "开启系统监控任务成功...");
//                        BetThread betThread = new BetThread(betType + "[BetThread]", betType);
//                        betThread.start();
//            this.resultService.addInfo(betType + "开启下单任务成功...");
//            log.info(betType + "首次注结束.....................");

            closeTime = jsonobj.getString("closeTime");
            String pBuydateId = jsonobj.getString("pnumber");
            String buydateId = jsonobj.getString("drawNumber");
//            if(closeTime != null && pBuydateId != null && buydateId != null) {
//                this.resultService.addInfo("上期" + pBuydateId + ",准备下注" + buydateId + "期");
//                AutoResult lastAutoResult = this.resultService.getLastResult();
//                if(!pBuydateId.equals(lastAutoResult.getBuydateId())) {
//                    log.info("上期开奖期数与查询期数不一致,预上期{}，上期{}", pBuydateId, lastAutoResult.getBuydateId());
//                    throw new Exception(betType + "上期开奖数据不匹配..请开奖后重新启动");
//                } else {
//                    boolean repairFlag = false;
//                    List<AutoHis> pAutoHisList = this.commonDao.queryAutoHisByBuydateIdAndBetType(pBuydateId, betType);
//                    if(pAutoHisList != null && pAutoHisList.size() > 0) {
//                        AutoHis pAutoHis = (AutoHis)pAutoHisList.get(0);
//                        if("00".equals(pAutoHis.getBuyResult())) {
//                            repairFlag = true;
//                        }
//                    } else {
//                        repairFlag = true;
//                    }
//
//                    if(repairFlag) {
//                        this.repairBetData(BetUtils.getCurrDateYYYYMMDD(), buydateId, betType);
//                        this.resultService.addInfo(betType + "数据不齐全，程序尝试修复数据...", "02");
//                    }
//
//                    if(this.checkStopRule(betType)) {
//                        this.stopBetForException("符合止损止盈规则,系统停止..");
//                    } else {
//                        List<AutoHis> preAutoList = this.commonDao.queryAutoHisByBuydateIdAndBetType(pBuydateId, betType);
//                        ResultHis preResultHis = this.commonDao.queryResultHisByBuydateId(pBuydateId);
//                        ResultHis fResultHis = this.commonDao.queryResultHisByResultDateAndFirst(BetUtils.getCurrDateYYYYMMDD());
//                        List<AutoHis> betList = this.simulateBet(preAutoList, "n", preResultHis, fResultHis.getBuydateId());
//                        BetBean betBean = new BetBean();
//                        betBean.setBuydateId(buydateId);
//                        betBean.setBetList(betList);
//                        this.realBetMap.put(buydateId + "_" + betType, betBean);
//                        this.doAllRealBet(buydateId);
//                        QueryResultThread queryResultThread = new QueryResultThread("[queryResultThread1]", betType);
//                        queryResultThread.start();
//                        this.resultService.addInfo(betType + "开启开奖结果查询任务成功...");
//                        CheckSystemThread checkSystemThread = new CheckSystemThread();
//                        checkSystemThread.start();
//                        this.resultService.addInfo(betType + "开启系统监控任务成功...");
//                        BetThread betThread = new BetThread(betType + "[BetThread]", betType);
//                        betThread.start();
//                        this.resultService.addInfo(betType + "开启下单任务成功...");
//                        log.info(betType + "首次注结束.....................");
//                    }
//                }
//            } else {
//                throw new Exception(betType + "取不到结果信息，可能登陆超时，请暂停系统，输入cookie重新开始");
//            }
        } catch (Exception var18) {
            log.info("首次下单失败！", var18);
            throw var18;
        }
    }

    public boolean doRealBetRetry(int times, String buydateId, String postJson) throws Exception {
        for(int i = 1; i <= times; ++i) {
            try {
                Thread.sleep((long)(2000 * i));
                boolean betflag = this.doRealBet(buydateId, postJson);
                if(betflag) {
                    return betflag;
                }

                log.info("下单失败，重试..");
                this.resultService.addInfo("下单失败，重试第" + i + "次..", "02");
            } catch (Exception var6) {
                if(i == times) {
                    throw var6;
                }

                log.info("下单失败，重试..");
                this.resultService.addInfo("下单失败，重试第" + i + "次..", "02");
            }
        }

        throw new Exception("重试" + times + "次下单失败！");
    }

    public boolean doRealBet(String buydateId, String postJson) throws Exception {
        try {
            log.info("实际下注的json串：{}");
            String posturl = EnvConfigService.getQueryBetUrl() + "/member/bet";
            Map<String, String> headerMap = new HashMap();
            headerMap.put("Origin", EnvConfigService.getQueryBetUrl());
            headerMap.put("Referer", EnvConfigService.getQueryBetUrl() + "/member/index");
            headerMap.put("Content-Type", "application/json");
            headerMap.put("Cookie", EnvConfigService.getCookie());
            if(this.realDoBuydateIdMap.get(buydateId) != null && "y".equals((String)this.realDoBuydateIdMap.get(buydateId))) {
                log.info("已成功下单了，返回ture,防止重复下单");
                return true;
            } else {
                String postresult = HttpUtils.postPayload(posturl, postJson, headerMap);
                log.info("下单返回结果：" + postresult);
                JSONObject rjson = JSONObject.parseObject(postresult);
                int status = rjson.getInteger("status").intValue();
                if(status == 0) {
                    log.info("下注成功，下注信息:{}", postJson);
                    this.resultService.addInfo("下注成功！继续...");
                    this.realDoBuydateIdMap.put(buydateId, "y");
                    return true;
                } else {
                    log.info("下注失败！，返回码：{}", Integer.valueOf(status));
                    return false;
                }
            }
        } catch (Exception var8) {
            log.error("实际下单失败！", var8);
            throw var8;
        }
    }

    /**
     * 修复下注数据
     * @param betDate
     * @param targetBetBuydateId
     * @param betType
     * @throws Exception
     */
    public void repairBetData(String betDate, String targetBetBuydateId, String betType) throws Exception {
        try {
            this.commonDao.saveOrUpdateResultHis(this.resultService.getCurrentAllResultRetry(6));
            log.info("补齐数据完毕");
            ResultHis fResultHis = this.commonDao.queryResultHisByResultDateAndFirst(betDate);
            if(fResultHis == null) {
                log.info("查询当天首次开奖记录失败！数据异常请重新开始执行任务..");
                this.stopBetForException("查询当天首次开奖记录失败！数据异常请重新开始执行任务..");
                throw new Exception("查询当天首次开奖记录失败！数据异常请重新开始执行任务");
            } else {
                int firstBuydateId = Integer.parseInt(fResultHis.getBuydateId()) + 1;
                int endBuydateId = Integer.parseInt(targetBetBuydateId);

                for(int iBuydateId = firstBuydateId; iBuydateId < endBuydateId; ++iBuydateId) {
                    List<AutoHis> iAutoHisList = this.commonDao.queryAutoHisByBuydateIdAndBetType(String.valueOf(iBuydateId), betType);
                    ResultHis currResult;
                    if(iAutoHisList != null && iAutoHisList.size() != 0) {
                        AutoHis currAutoHis = (AutoHis)iAutoHisList.get(0);
                        if("00".equals(currAutoHis.getBuyResult())) {
                            currResult = this.commonDao.queryResultHisByBuydateId(String.valueOf(iBuydateId));
                            List<AutoHis> repairAutoList = new ArrayList();
                            Iterator var12 = iAutoHisList.iterator();

                            while(var12.hasNext()) {
                                AutoHis rCurrAutoHis = (AutoHis)var12.next();

                                if("dx".equals(betType)) {
                                    if("D".equals(rCurrAutoHis.getBuyWhat()) && BetUtils.isBig(currResult.getResultByNum(rCurrAutoHis.getBuyNum()))) {
                                        rCurrAutoHis.setBuyResult("01");
                                        rCurrAutoHis.setBuyMoneytake(rCurrAutoHis.getPreAmount());
                                        rCurrAutoHis.setBuyRMoneytake(new BigDecimal(rCurrAutoHis.getPreAmount().doubleValue() * (Double.parseDouble(EnvConfigService.getMoneytakeRate()) - 1.0D)));

                                        rCurrAutoHis.setBuyMoneyTakeReadly(rCurrAutoHis.getPreAmountReadly());
                                        rCurrAutoHis.setBuyRMoneyTakeReadly(new BigDecimal(rCurrAutoHis.getPreAmountReadly().doubleValue() * (Double.parseDouble(EnvConfigService.getMoneytakeRate()) - 1.0D)));
                                    } else {
                                        rCurrAutoHis.setBuyResult("02");
                                        rCurrAutoHis.setBuyMoneytake(new BigDecimal("-" + rCurrAutoHis.getPreAmount().intValue()));
                                        rCurrAutoHis.setBuyRMoneytake(new BigDecimal("-" + rCurrAutoHis.getPreAmount().intValue()));

                                        rCurrAutoHis.setBuyMoneyTakeReadly(new BigDecimal("-" + rCurrAutoHis.getPreAmountReadly().intValue()));
                                        rCurrAutoHis.setBuyRMoneyTakeReadly(new BigDecimal("-" + rCurrAutoHis.getPreAmountReadly().intValue()));
                                    }
                                } else {
                                    if(!"ds".equals(betType)) {
                                        throw new Exception("玩法错误！");
                                    }

                                    if("S".equals(rCurrAutoHis.getBuyWhat()) && BetUtils.isDouble(currResult.getResultByNum(rCurrAutoHis.getBuyNum()))) {
                                        rCurrAutoHis.setBuyResult("01");
                                        rCurrAutoHis.setBuyMoneytake(rCurrAutoHis.getPreAmount());
                                        rCurrAutoHis.setBuyRMoneytake(new BigDecimal(rCurrAutoHis.getPreAmount().doubleValue() * (Double.parseDouble(EnvConfigService.getMoneytakeRate()) - 1.0D)));

                                        rCurrAutoHis.setBuyMoneyTakeReadly(rCurrAutoHis.getPreAmountReadly());
                                        rCurrAutoHis.setBuyRMoneyTakeReadly(new BigDecimal(rCurrAutoHis.getPreAmountReadly().doubleValue() * (Double.parseDouble(EnvConfigService.getMoneytakeRate()) - 1.0D)));
                                    } else {
                                        rCurrAutoHis.setBuyResult("02");
                                        rCurrAutoHis.setBuyMoneytake(new BigDecimal("-" + rCurrAutoHis.getPreAmount().intValue()));
                                        rCurrAutoHis.setBuyRMoneytake(new BigDecimal("-" + rCurrAutoHis.getPreAmount().intValue()));

                                        rCurrAutoHis.setBuyMoneyTakeReadly(new BigDecimal("-" + rCurrAutoHis.getPreAmountReadly().intValue()));
                                        rCurrAutoHis.setBuyRMoneyTakeReadly(new BigDecimal("-" + rCurrAutoHis.getPreAmountReadly().intValue()));
                                    }
                                }

                                rCurrAutoHis.setCurrBuyresult(currResult.getResultArray());
                                repairAutoList.add(rCurrAutoHis);
                            }



                            this.commonDao.updateAutoHisByBuydateId(repairAutoList);
                            log.info("数据修复：{}期有下注记录，但是没有开奖,补齐开奖数据", Integer.valueOf(iBuydateId));
                        }
                    } else if(firstBuydateId != iBuydateId) {
                        List<AutoHis> fLastAutoHisList = this.commonDao.queryAutoHisByBuydateIdAndBetType(String.valueOf(iBuydateId - 1), betType);
                        currResult = this.commonDao.queryResultHisByBuydateId(String.valueOf(iBuydateId - 1));
                        this.commonDao.saveAutoHisList(this.simulateBet(fLastAutoHisList, "y", currResult, fResultHis.getBuydateId()));
                        log.info("第{}期模拟下注成功", Integer.valueOf(iBuydateId));
                    } else {
                        List<AutoHis> fLastAutoHisList = new ArrayList();

                        for(int i = 1; i <= 10; ++i) {
                            AutoHis fLastAutoHis = new AutoHis();
                            fLastAutoHis.setAccountId(EnvConfigService.getAccountId());
                            fLastAutoHis.setFirstFlag("y");
                            fLastAutoHis.setPreAmount(new BigDecimal(EnvConfigService.getPreAmount()));
                            fLastAutoHis.setPreAmountReadly( new BigDecimal(EnvConfigService.getPreAmount()));
                            fLastAutoHis.setBuyNum(String.valueOf(i));
                            fLastAutoHis.setBuyType(betType);
                            fLastAutoHis.setBuydateId(fResultHis.getBuydateId());
                            fLastAutoHis.setFirstFlag("n");
                            fLastAutoHis.setBuyResult("00");
                            fLastAutoHis.setDieCount(new BigDecimal("0"));
                            fLastAutoHis.setDieCountReadly(new BigDecimal("0"));
                            fLastAutoHisList.add(fLastAutoHis);
                        }

                        this.commonDao.saveAutoHisList(this.simulateBet(fLastAutoHisList, "y", fResultHis, fResultHis.getBuydateId()));
                        log.info("当天第二期{}模拟下注成功", Integer.valueOf(iBuydateId));
                    }
                }

                log.info("数据修复结束...");
            }
        } catch (Exception var14) {
            log.error("修复投注数据失败！", var14);
            throw var14;
        }
    }

    /**
     * 构建下注信息
     * @param lastAutoHisList
     * @param simulateFlag
     * @param lastResultHis
     * @param firstBuydateId
     * @return
     * @throws Exception
     */
    public List<AutoHis> simulateBet(List<AutoHis> lastAutoHisList, String simulateFlag, ResultHis lastResultHis, String firstBuydateId) throws Exception {
        try {
            if(lastAutoHisList != null && lastAutoHisList.size() != 0) {
                List<AutoHis> simulateAutoHisList = new ArrayList();

                AutoHis simulateAutoHis;
                for(Iterator var6 = lastAutoHisList.iterator(); var6.hasNext(); simulateAutoHisList.add(simulateAutoHis)) {
                    AutoHis lastAutoHis = (AutoHis)var6.next();
                    simulateAutoHis = new AutoHis();
                    simulateAutoHis.setBuyType(lastAutoHis.getBuyType());
                    simulateAutoHis.setBuyNum(lastAutoHis.getBuyNum());
                    simulateAutoHis.setAccountId(lastAutoHis.getAccountId());
                    simulateAutoHis.setLastBuyresult(lastAutoHis.getCurrBuyresult());
                    simulateAutoHis.setSimulateFlag(simulateFlag);
                    simulateAutoHis.setBuyMoneytake(new BigDecimal("0"));
                    simulateAutoHis.setBuyRMoneytake(new BigDecimal("0"));
                    simulateAutoHis.setBuyMoneyTakeReadly(new BigDecimal("0"));
                    simulateAutoHis.setBuyRMoneyTakeReadly(new BigDecimal("0"));
                    simulateAutoHis.setBuydateId(String.valueOf(Integer.parseInt(lastAutoHis.getBuydateId()) + 1));
                    simulateAutoHis.setPreAmount(lastAutoHis.getPreAmount());
                    simulateAutoHis.setPreAmountReadly(lastAutoHis.getPreAmountReadly());
                    simulateAutoHis.setLastBuyresult(lastResultHis.getResultArray());
                    simulateAutoHis.setFirstFlag("n");
                    simulateAutoHis.setDieCount(lastAutoHis.getDieCount());
                    simulateAutoHis.setDieCountReadly(lastAutoHis.getDieCountReadly());

                    if(firstBuydateId.equals(lastAutoHis.getBuydateId())) {
                        /**
                         * 判断首次下注和上次下注id是一样进入
                         */
                        if("dx".equals(lastAutoHis.getBuyType())) {
                            /*下注类型为大小*/
                            if(BetUtils.isBig(lastResultHis.getResultByNum(lastAutoHis.getBuyNum()))) {
                                /*如果下注大于5*/
                                if("y".equals(EnvConfigService.firstBetTypeFlag)) {
                                    simulateAutoHis.setBuyWhat("D");
                                    simulateAutoHis.setBetRule("21");
                                } else {
                                    simulateAutoHis.setBuyWhat("X");
                                    simulateAutoHis.setBetRule("11");
                                }
                            } else if("y".equals(EnvConfigService.firstBetTypeFlag)) {
                                simulateAutoHis.setBuyWhat("X");
                                simulateAutoHis.setBetRule("11");
                            } else {
                                simulateAutoHis.setBuyWhat("D");
                                simulateAutoHis.setBetRule("21");
                            }

                            simulateAutoHis.setBuyAmount(lastAutoHis.getPreAmount());
                            simulateAutoHis.setBuyAmountReadly(lastAutoHis.getPreAmountReadly());
                            //首次下注标志
                            simulateAutoHis.setFirstFlag("y");
                        } else {
                            /*下注类型为单双*/
                            if(!"ds".equals(lastAutoHis.getBuyType())) {
                                throw new Exception("玩法不正确!");
                            }

                            if(BetUtils.isDouble(lastResultHis.getResultByNum(lastAutoHis.getBuyNum()))) {
                                if("y".equals(EnvConfigService.firstBetTypeFlag)) {
                                    simulateAutoHis.setBuyWhat("S");
                                    simulateAutoHis.setBetRule("21");
                                } else {
                                    simulateAutoHis.setBuyWhat("D");
                                    simulateAutoHis.setBetRule("11");
                                }
                            } else if("y".equals(EnvConfigService.firstBetTypeFlag)) {
                                simulateAutoHis.setBuyWhat("D");
                                simulateAutoHis.setBetRule("11");
                            } else {
                                simulateAutoHis.setBuyWhat("S");
                                simulateAutoHis.setBetRule("21");
                            }

                            simulateAutoHis.setBuyAmount(lastAutoHis.getPreAmount());
                            simulateAutoHis.setBuyAmountReadly(lastAutoHis.getPreAmountReadly());
                            //首次下注标志
                            simulateAutoHis.setFirstFlag("y");
                        }
                    } else {
                        String currPreAmount = "0";
                        String currPreAmountReadly = "0";
                        if(("25".equals(lastAutoHis.getBetRule()) || "15".equals(lastAutoHis.getBetRule())) && "02".equals(lastAutoHis.getBuyResult())) {

                            /*穿版打法判断*/
                            if("y".equals(EnvConfigService.dieMoneyFlag)) {
                                currPreAmount = String.valueOf(lastAutoHis.getPreAmount().intValue() * 2 + Integer.parseInt(EnvConfigService.getPreAmount()));
                                currPreAmountReadly = String.valueOf(lastAutoHis.getPreAmountReadly().intValue() * 2 + Integer.parseInt(EnvConfigService.getPreAmount()));
                            } else {
                                currPreAmount = String.valueOf(lastAutoHis.getPreAmount().intValue() + Integer.parseInt(EnvConfigService.getPreAmount()));
                                currPreAmountReadly = String.valueOf(lastAutoHis.getPreAmountReadly().intValue() + Integer.parseInt(EnvConfigService.getPreAmount()));
                            }

                            if("dx".equals(lastAutoHis.getBuyType())) {
                                /**
                                 * 大小玩法
                                 */
                                if(BetUtils.isBig(lastResultHis.getResultByNum(lastAutoHis.getBuyNum()))) {
                                    /*如果下注大于5*/
                                    simulateAutoHis.setBuyWhat("X");
                                    simulateAutoHis.setBetRule("11");
                                } else {
                                    simulateAutoHis.setBuyWhat("D");
                                    simulateAutoHis.setBetRule("21");
                                }

                                simulateAutoHis.setBuyAmount(new BigDecimal(currPreAmount));
                                simulateAutoHis.setBuyAmountReadly(new BigDecimal(currPreAmountReadly));
                                simulateAutoHis.setPreAmount(new BigDecimal(currPreAmount));
                                simulateAutoHis.setPreAmountReadly(new BigDecimal(currPreAmountReadly));
                                simulateAutoHis.setDieCount(new BigDecimal(simulateAutoHis.getDieCount().intValue() + 1));
                                simulateAutoHis.setDieCountReadly(new BigDecimal(simulateAutoHis.getDieCountReadly().intValue() + 1));
                            } else {
                                /**
                                 * 单双玩法
                                 */
                                if(!"ds".equals(lastAutoHis.getBuyType())) {
                                    throw new Exception("玩法不正确！");
                                }

                                if(BetUtils.isDouble(lastResultHis.getResultByNum(lastAutoHis.getBuyNum()))) {
                                    /*为双数进入*/
                                    simulateAutoHis.setBuyWhat("D");
                                    simulateAutoHis.setBetRule("11");
                                } else {
                                    simulateAutoHis.setBuyWhat("S");
                                    simulateAutoHis.setBetRule("21");
                                }

                                simulateAutoHis.setBuyAmount(new BigDecimal(currPreAmount));
                                simulateAutoHis.setBuyAmountReadly(new BigDecimal(currPreAmountReadly));
                                simulateAutoHis.setPreAmount(new BigDecimal(currPreAmount));
                                simulateAutoHis.setPreAmountReadly(new BigDecimal(currPreAmountReadly));
                                simulateAutoHis.setDieCount(new BigDecimal(simulateAutoHis.getDieCount().intValue() + 1));
                                simulateAutoHis.setDieCountReadly(new BigDecimal(simulateAutoHis.getDieCountReadly().intValue() + 1));
                            }
                            log.info("投注生成规则判断"+lastResultHis.toString());
                        } else if("01".equals(lastAutoHis.getBuyResult())) {
                            /*投注结果为01，赢*/
                            if("dx".equals(lastAutoHis.getBuyType())) {
                                if(BetUtils.isBig(lastResultHis.getResultByNum(lastAutoHis.getBuyNum()))) {
                                    simulateAutoHis.setBuyWhat("D");
                                    simulateAutoHis.setBetRule("21");
                                } else {
                                    simulateAutoHis.setBuyWhat("X");
                                    simulateAutoHis.setBetRule("11");
                                }

                                simulateAutoHis.setBuyAmount(lastAutoHis.getPreAmount());
                                simulateAutoHis.setBuyAmountReadly(lastAutoHis.getPreAmountReadly());
                            } else {
                                if(!"ds".equals(lastAutoHis.getBuyType())) {
                                    throw new Exception("玩法不正确");
                                }

                                if(BetUtils.isDouble(lastResultHis.getResultByNum(lastAutoHis.getBuyNum()))) {
                                    /*为双数进入*/
                                    simulateAutoHis.setBuyWhat("S");
                                    simulateAutoHis.setBetRule("21");
                                } else {
                                    simulateAutoHis.setBuyWhat("D");
                                    simulateAutoHis.setBetRule("11");
                                }

                                simulateAutoHis.setBuyAmount(lastAutoHis.getPreAmount());
                                simulateAutoHis.setBuyAmountReadly(lastAutoHis.getPreAmountReadly());
                                log.info("投注生成赢"+lastResultHis.toString());
                            }
                        } else {
                            /*投注结果生成*/
                            simulateAutoHis.setBuyWhat(BetUtils.getbuyWhatFromBetRule(BetUtils.getNextBetRule(lastAutoHis.getBetRule()), lastAutoHis.getBuyType()));
                            /*投注规则生成*/
                            simulateAutoHis.setBetRule(BetUtils.getNextBetRule(lastAutoHis.getBetRule()));
                            simulateAutoHis.setBuyAmount(new BigDecimal(lastAutoHis.getBuyAmount().intValue() * 2 + lastAutoHis.getPreAmount().intValue()));
                            simulateAutoHis.setBuyAmountReadly(new BigDecimal(lastAutoHis.getBuyAmountReadly().intValue() * 2 + lastAutoHis.getPreAmountReadly().intValue()));
                            log.info("投注生成执行了最后判断"+lastResultHis.toString());
                        }
                    }

                    /**
                     * 前置数据操作
                     */
                    if("y".equals(simulateFlag)) {
                        ResultHis currResult = this.commonDao.queryResultHisByBuydateId(String.valueOf(Integer.parseInt(lastAutoHis.getBuydateId()) + 1));
                        if("dx".equals(simulateAutoHis.getBuyType())) {
                            if(BetUtils.isBig(currResult.getResultByNum(simulateAutoHis.getBuyNum()))) {
                                if("D".equals(simulateAutoHis.getBuyWhat())) {
                                    simulateAutoHis.setBuyResult("01");
                                    simulateAutoHis.setBuyMoneytake(simulateAutoHis.getBuyAmount());
                                    simulateAutoHis.setBuyMoneyTakeReadly(simulateAutoHis.getBuyAmountReadly());
                                } else {
                                    simulateAutoHis.setBuyResult("02");
                                    simulateAutoHis.setBuyMoneytake(new BigDecimal("-" + simulateAutoHis.getBuyAmount().doubleValue()));
                                    simulateAutoHis.setBuyMoneyTakeReadly(new BigDecimal("-" + simulateAutoHis.getBuyAmountReadly().doubleValue()));
                                }
                            } else if("X".equals(simulateAutoHis.getBuyWhat())) {
                                simulateAutoHis.setBuyResult("01");
                                simulateAutoHis.setBuyMoneytake(simulateAutoHis.getBuyAmount());
                                simulateAutoHis.setBuyMoneyTakeReadly(simulateAutoHis.getBuyAmountReadly());
                            } else {
                                simulateAutoHis.setBuyResult("02");
                                simulateAutoHis.setBuyMoneytake(new BigDecimal("-" + simulateAutoHis.getBuyAmount().doubleValue()));
                                simulateAutoHis.setBuyMoneyTakeReadly(new BigDecimal("-" + simulateAutoHis.getBuyAmountReadly().doubleValue()));
                            }

                            simulateAutoHis.setCurrBuyresult(currResult.getResultArray());
                        } else {
                            if(!"ds".equals(simulateAutoHis.getBuyType())) {
                                throw new Exception("玩法不正确！");
                            }

                            if(BetUtils.isDouble(currResult.getResultByNum(simulateAutoHis.getBuyNum()))) {
                                if("S".equals(simulateAutoHis.getBuyWhat())) {
                                    simulateAutoHis.setBuyResult("01");
                                    simulateAutoHis.setBuyMoneytake(simulateAutoHis.getBuyAmount());
                                    simulateAutoHis.setBuyMoneyTakeReadly(simulateAutoHis.getBuyAmountReadly());
                                } else {
                                    simulateAutoHis.setBuyResult("02");
                                    simulateAutoHis.setBuyMoneytake(new BigDecimal("-" + simulateAutoHis.getBuyAmount().doubleValue()));
                                    simulateAutoHis.setBuyMoneyTakeReadly(new BigDecimal("-" + simulateAutoHis.getBuyAmountReadly().doubleValue()));
                                }
                            } else if("D".equals(simulateAutoHis.getBuyWhat())) {
                                simulateAutoHis.setBuyResult("01");
                                simulateAutoHis.setBuyMoneytake(simulateAutoHis.getBuyAmount());
                                simulateAutoHis.setBuyMoneyTakeReadly(simulateAutoHis.getBuyAmountReadly());
                            } else {
                                simulateAutoHis.setBuyResult("02");
                                simulateAutoHis.setBuyMoneytake(new BigDecimal("-" + simulateAutoHis.getBuyAmount().doubleValue()));
                                simulateAutoHis.setBuyMoneyTakeReadly(new BigDecimal("-" + simulateAutoHis.getBuyAmountReadly().doubleValue()));
                            }

                            simulateAutoHis.setCurrBuyresult(currResult.getResultArray());
                        }
                    } else {
                        simulateAutoHis.setBuyResult("00");
                    }

                    //判断是否真实数据
                    if(CarStatus.getCarStatus(lastAutoHis.getBuyType(),lastAutoHis.getBuyNum())){
                        simulateAutoHis.setReadlyfalg("true");
                    }else{
                        simulateAutoHis.setReadlyfalg("false");
                    }

                    //反打设置真实投注投注数据
//                    simulateAutoHis.setBuyWhatReadly(BetUtils.reversalBuild(simulateAutoHis.getBuyType(),simulateAutoHis.getBuyWhat()));

                    //车辆下注设置修改开关复位
                    if(  SetCarStatus.getCarStatus( simulateAutoHis.getBuyType() ,simulateAutoHis.getBuyNum() ) && !"y".equals(simulateFlag)){
                        //设置新数据时
                        simulateAutoHis.setBuyAmountReadly( BetStatus.getPreAmount( simulateAutoHis.getBuyType() ,simulateAutoHis.getBuyNum() ) );
                        simulateAutoHis.setPreAmountReadly( BetStatus.getPreAmount( simulateAutoHis.getBuyType() ,simulateAutoHis.getBuyNum() ) );
                        SetCarStatus.setCarStatus( simulateAutoHis.getBuyType() ,simulateAutoHis.getBuyNum() ,false );
                        BetStatus.setDieCount( simulateAutoHis.getBuyType() ,simulateAutoHis.getBuyNum() ,simulateAutoHis.getDieCountReadly());
                    }else if(!SetCarStatus.getCarStatus( simulateAutoHis.getBuyType() ,simulateAutoHis.getBuyNum() ) && !"y".equals(simulateFlag)){
                        //车辆状态反写
                        BetStatus.setBuyAmount( simulateAutoHis.getBuyType() ,simulateAutoHis.getBuyNum() ,simulateAutoHis.getBuyAmountReadly());
                        BetStatus.setPreAmount( simulateAutoHis.getBuyType() ,simulateAutoHis.getBuyNum() ,simulateAutoHis.getPreAmountReadly());
                        BetStatus.setDieCount( simulateAutoHis.getBuyType() ,simulateAutoHis.getBuyNum() ,simulateAutoHis.getDieCountReadly());
                    }


                }

                return simulateAutoHisList;
            } else {
                throw new Exception("没有获取到上期投注情况");
            }
        } catch (Exception var10) {
            log.error("模拟下单失败！", var10);
            throw new Exception("模拟下单失败！" + var10.getMessage());
        }
    }
}
